package org.wattdepot.cli.commands;

import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Provides the command to obtain the carbon content.
 * 
 * @author David Joel Lazaro
 */
public class CarbonContentCommand implements Command {

  /**
   * Calls the carbonContent method.
   * 
   * @param userInput The user input.
   * @param client The WattDepotClient
   * @return Returns the method call with the proper parameters.
   */
  public String doCommand(List<String> userInput, WattDepotClient client) {
    return carbonContent(userInput, client);
  }

  /**
   * Computes the carbon content of the source.
   * 
   * @param commandParam The input from user.
   * @param client The WattDepotClient
   * @return Returns the carbon content for the given source.
   */
  private String carbonContent(List<String> commandParam, WattDepotClient client) {
    StringBuffer buff = new StringBuffer();
    SourceChecker check = new SourceChecker();
    TStampChecker stampCheck = new TStampChecker();
    if (!check.sourceChecker(commandParam.get(1), client)) {
      return "Invalid source.";
    }

    if (!stampCheck.checkTStamp(commandParam.get(2))) {
      return "ERROR: Timestamp error.";
    }

    int interval = Integer.parseInt(commandParam.get(4));

    try {
      XMLGregorianCalendar start = Tstamp.makeTimestamp(commandParam.get(2));
      XMLGregorianCalendar end = Tstamp.incrementDays(start, 1);
      // end = Tstamp.incrementMinutes(end, interval);

      double carbonGenerated = client.getCarbonEmitted(commandParam.get(1), start, end, interval);
      double energyGenerated = client.getEnergyGenerated(commandParam.get(1), start, end, interval);

      double carbonContent = carbonGenerated / energyGenerated;
      double carbonFinal = carbonContent * 1000000;

      buff.append(Math.round(carbonFinal));
      buff.append(" lbs CO2/MWh");
    }
    catch (NotAuthorizedException e) {
      e.printStackTrace();
    }
    catch (ResourceNotFoundException e) {
      e.printStackTrace();
    }
    catch (BadXmlException e) {
      e.printStackTrace();
    }
    catch (MiscClientException e) {
      e.printStackTrace();
    }
    catch (Exception e) {
      e.printStackTrace();
    }

    return buff.toString();

  }

}
